import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)


import login from '@/views/login'
import layout from '@/layout'
import ask from '@/views/ask'
import home from '@/views/home'
import mine from '@/views/mine'
import video from '@/views/video'
import edit from '@/views/mine/edit'
import particulars from '@/views/particulars'
import chat from '@/views/mine/chat'


const routes = [{
    path: '',
    redirect: '/layout/home'
  }, {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'chat',
    path: '/mine/chat',
    component: chat,
    meta: {
      needLogin: true
    }
  },
  {
    name: 'particulars',
    path: '/particulars',
    component: particulars
  }, {
    name: 'edit',
    path: '/mine/edit',
    component: edit,
    meta: {
      needLogin: true
    }
  }, {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [{
        name: 'ask',
        path: 'ask',
        component: ask
      },
      {
        name: 'home',
        path: 'home',
        component: home,
        meta: {
          needKeep: true
        }
      },
      {
        name: 'mine',
        path: 'mine',
        component: mine,
        meta: {
          needLogin: true
        }
      },
      {
        name: 'video',
        path: 'video',
        component: video
      }
    ]
  }
]

const router = new VueRouter({
  routes
})



// 导入store
import store from '@/store'

import {
  Toast
} from 'vant';

// 路由对象加全局前置守卫
// to：   去哪
// from:  从哪来
// next 是一个函数，调用它代表放行（跳转），不调用代表不放行（不跳转）
router.beforeEach((to, from, next) => {

  // 判断去的页面是不是需要登录的页面
  // 需要先给路由打上标签
  if (to.meta.needLogin) {
    // 证明是需要登录的页面 
    // 如何判断有没有登录？
    if (store.state.tokenObj.token) {

      next()
    } else {
      // 代表没登录，打回登录页
      // 页就是放行到登录页
      // 弹出一个轻提示
      Toast.fail('请先登录')
      next({
        name: 'login',
        query: {
          back: to.path
        }
      })
    }

  } else {

    next()
  }

})


export default router